﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using Newtonsoft.Json.Linq;
using log4net;

public partial class PlaceOrder : System.Web.UI.Page
{
    protected JObject jsonResponse;

    protected string paymentID;
    protected string paymentState;
    protected string finalAmount;
    protected string currency;
    protected string transactionID;
    protected string payerFirstName;
    protected string payerLastName;
    protected string recipientName;
    protected string addressLine1;
    protected string addressLine2;
    protected string city;
    protected string state;
    protected string postalCode;
    protected string countryCode;
    protected string addressLines;

    private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

    protected void Page_Load(object sender, EventArgs e)
    {
        log4net.Config.XmlConfigurator.Configure();

        if (Session["csrf"] == null)
        {
            log.Info(
                "Session expired: force redirect back to Index."
            );

            Response.Redirect("Index.aspx");
        }

        Session["paymentID"] = Request.QueryString["paymentId"];
        Session["payerID"] = Request.QueryString["payerID"];

        jsonResponse = PayPalMethods.lookUpPaymentDetails(Session["accessToken"].ToString(), Request.QueryString["paymentId"]);

        recipientName = jsonResponse["payer"]["payer_info"]["shipping_address"]["recipient_name"].ToString();
        addressLine1 = jsonResponse["payer"]["payer_info"]["shipping_address"]["line1"].ToString();
        addressLine2 = (jsonResponse["payer"]["payer_info"]["shipping_address"]["line2"] != null) ? jsonResponse["payer"]["payer_info"]["shipping_address"]["line2"].ToString() : "";
        city = jsonResponse["payer"]["payer_info"]["shipping_address"]["city"].ToString();
        state = jsonResponse["payer"]["payer_info"]["shipping_address"]["state"].ToString();
        postalCode = jsonResponse["payer"]["payer_info"]["shipping_address"]["postal_code"].ToString();
        countryCode = jsonResponse["payer"]["payer_info"]["shipping_address"]["country_code"].ToString();

        // format address lines so no blank line
        List<string> addr = new List<string>();

        if (addressLine1 != "")
            addr.Add(addressLine1);
        if (addressLine2 != "")
            addr.Add(addressLine2);

        addressLines = string.Join("<br />", addr);

    }
}